package com.lenovo.dh.voteclient.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.lenovo.dh.voteclient.R;
import com.lenovo.dh.voteclient.bean.Topics.Topic;
import com.lenovo.dh.voteclient.utils.HttpUtils;
import com.lenovo.dh.voteclient.utils.Utils;
import com.lenovo.nova.util.debug.MyLog;
import com.lenovo.nova.util.network.NetworkManager;
import com.lenovo.nova.util.parse.JsonToBeanParser;

public class VoteService implements Contans {
	private Context mContext;
	private List<Handler> handlerCallbacks;

	public VoteService(Context context) {
		this.mContext = context;
		handlerCallbacks = new ArrayList<Handler>();
	}

	public void registerCallback(ServiceHandler serviceHandler) {
		handlerCallbacks.add(serviceHandler.getHandler());
	}

	public void unRegisterCallback(ServiceHandler serviceHandler) {
		handlerCallbacks.remove(serviceHandler.getHandler());
	}

	public boolean checkNetworkStatus() {

		if (mContext != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) mContext
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mNetworkInfo = mConnectivityManager
					.getActiveNetworkInfo();
			if (mNetworkInfo != null) {
				return mNetworkInfo.isAvailable();
			}
		}
		return false;

		/*
		 * ConnectivityManager mConnectivity = (ConnectivityManager) mContext
		 * .getSystemService(Context.CONNECTIVITY_SERVICE); TelephonyManager
		 * mTelephony = (TelephonyManager) mContext
		 * .getSystemService(Context.TELEPHONY_SERVICE); NetworkInfo info =
		 * mConnectivity.getActiveNetworkInfo(); if (info == null ||
		 * !mConnectivity.getBackgroundDataSetting()) { return false; } int
		 * netType = info.getType(); int netSubtype = info.getSubtype();
		 * 
		 * if (netType == ConnectivityManager.TYPE_WIFI) { return
		 * info.isConnected(); } else if (netType ==
		 * ConnectivityManager.TYPE_MOBILE && netSubtype ==
		 * TelephonyManager.NETWORK_TYPE_UMTS && !mTelephony.isNetworkRoaming())
		 * { return info.isConnected(); } else { return false; }
		 */
	}

	public void exceLoadCurrentTopic() {
		LoadCurrentTask loadCurrentTask = new LoadCurrentTask();
		loadCurrentTask.execute(false, getTopicURL(), null, null, null);
	}

	public void exceCommitCurrentTopic(int currentOptionid, int topicId,
			String Imei, String name) {
		Log.d("shiqc1", "currentOptionid:" + currentOptionid + " Imei :" + Imei
				+ " name:" + name);
		CommitCurrentTask commitCurrentTask = new CommitCurrentTask();
		commitCurrentTask.execute(getCommitURL(), currentOptionid, Imei, name,
				topicId);
	}

	abstract class NetworkTask extends AsyncTask<Object, Object, Object> {
		protected NetworkManager netManager;
		protected ProgressDialog dialog;
		protected boolean isConnectted;;
		protected boolean isTimeout = false;;
		Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				if(dialog.isShowing()) {
					dialog.dismiss();
					Toast.makeText(mContext, R.string.net_out, 1).show();
					isTimeout = true;
				}
			};
		};

		public NetworkTask() {
			netManager = new NetworkManager(mContext);
			dialog = new ProgressDialog(mContext);
			isConnectted = checkNetworkStatus();
		}

		@Override
		protected void onPreExecute() {
			if (isConnectted) {
				dialog.setMessage(mContext.getResources().getString(
						getMessageId()));
				dialog.show();
				handler.sendMessageDelayed(Message.obtain(), 10000);
				dialog.setCanceledOnTouchOutside(false);
				dialog.setCancelable(false);
			} else {
				Toast.makeText(mContext, R.string.network_error,
						Toast.LENGTH_LONG).show();
			}
			super.onPreExecute();
		}

		@Override
		protected Object doInBackground(Object... params) {
			if (isConnectted && !isTimeout) {
				return doInBackgroundEx(params);
			}
			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);
			dialog.dismiss();
			if (isConnectted) {
				onPostExecuteEx(result);
			}
		}

		protected abstract int getMessageId();

		protected abstract Object doInBackgroundEx(Object... params);

		protected abstract void onPostExecuteEx(Object result);
	}

	class CommitCurrentTask extends NetworkTask {

		public CommitCurrentTask() {
			super();
		}

		@Override
		protected int getMessageId() {
			return R.string.commit_msg;
		}

		@Override
		protected Object doInBackgroundEx(Object... params) {
			int result = -1;
			String url = (String) params[0];
			int optionsId = (Integer) params[1];
			String ime = (String) params[2];
			String name = (String) params[3];
			int topicId = (Integer) params[4];
			Log.d("shiqc1", "currentOptionid:" + optionsId + " Imei :" + ime
					+ " name:" + name + " topicId:" + topicId + " url :" + url);
			Map<String, String> commit_params = new HashMap<String, String>();
			commit_params.put("option_name", name);
			commit_params.put("ime", ime);
			commit_params.put("topic_id", String.valueOf(topicId));
			commit_params.put("option_id", String.valueOf(optionsId));
			try {
				String content = HttpUtils.sendGetRequest(url, commit_params,
						"UTF-8");
				result = Integer.parseInt(content);
				Log.d("shiqc1", "commit result:" + result);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result;
		}

		@Override
		protected void onPostExecuteEx(Object result) {
			int isSuccess = (Integer) result;
			switch (isSuccess) {
			case 0:
				Toast.makeText(mContext, R.string.success_msg,
						Toast.LENGTH_LONG).show();
				break;
			case 1:
				int randomRes = new Random().nextInt(4);
				int resId = R.string.commit_repeat_0;
				switch (randomRes) {
				case 0:
					resId = R.string.commit_repeat_0;
					break;
				case 1:
					resId = R.string.commit_repeat_1;
					break;
				case 2:
					resId = R.string.commit_repeat_2;
					break;
				case 3:
					resId = R.string.commit_repeat_3;
					break;

				default:
					break;
				}
				if (mContext.getResources().getString(R.string.spe_name_0)
						.equals(Utils.getNameByShare(mContext))) {
					resId = R.string.commit_repeat_spe;
				}
				Toast.makeText(mContext, resId, Toast.LENGTH_LONG).show();
				break;
			case 2:
				Toast.makeText(mContext, R.string.topic_pass, Toast.LENGTH_LONG)
						.show();
				break;
			case -1:
				Toast.makeText(mContext, R.string.error, Toast.LENGTH_LONG)
				.show();
				break;
			default:
				Toast.makeText(mContext, R.string.error, Toast.LENGTH_LONG)
						.show();
				break;
			}
		}

	}

	class LoadCurrentTask extends NetworkTask {
		@SuppressWarnings("unchecked")
		@Override
		protected Object doInBackgroundEx(Object... params) {
			boolean isPost = false;
			String strUrl = null;
			List<BasicNameValuePair> requestHead = null;
			List<BasicNameValuePair> postBody = null;
			List<BasicNameValuePair> respondHead = null;
			try {
				isPost = (Boolean) params[0];
				strUrl = (String) params[1];
				requestHead = (List<BasicNameValuePair>) params[2];
				postBody = (List<BasicNameValuePair>) params[3];
				respondHead = (List<BasicNameValuePair>) params[4];
			} catch (IndexOutOfBoundsException e) {
				MyLog.e(e + "  " + params);
				e.printStackTrace();
			}

			if (netManager == null) {
				MyLog.e("networkManager is null");
				return null;
			}
			Log.d("shiqc1", "doInBackgroundEx....start ..strUrl:" + strUrl);
			String result = netManager.connectionWithApache(isPost, strUrl,
					requestHead, postBody, respondHead);
			Log.d("shiqc1", "doInBackgroundEx....end ..");
			return result;
		}

		@Override
		protected void onPostExecuteEx(Object result) {
			// final Topics topics = new Topics();
			// List<Topics.Topic> mAllTopic = topics.mList;
			Topic topic = new Topic();
			String json = (String) result;
			boolean isSuccess = false;
			if (result != null) {
				JSONObject jsonObject = null;
				try {
					jsonObject = new JSONObject(json);
					JsonToBeanParser.getInstance().fillBeanWithJson(topic,
							jsonObject);
					isSuccess = true;
				} catch (Exception e) {
					e.printStackTrace();
					Log.d("shiqc1", e.toString());
				}
				// JsonToBeanParser.getInstance().fillBeanWithJson(mAllTopic,
				// jsonArray, new OnJSONFillBeanHelper() {
				// @Override
				// public Bean getNewBean() {
				// return topics.newEntity();
				// }
				// });

			}
			Log.d("shiqc1", "onPostExecuteEx.....topic:." + topic);
			Message message = new Message();
			message.what = MSG_LOAD_FINISH;
			message.obj = topic;
			for (Handler handler : handlerCallbacks) {
				handler.sendMessage(message);
			}

		}

		@Override
		protected int getMessageId() {
			return R.string.current_topic_loading_title;
		}
	}

	private String getTopicURL() {
		return ROOT_URL + "/vote?method=gettopic";
	}

	private String getCommitURL() {
		return ROOT_URL + "/vote?method=commit";
	}
}
